<template>
  <div>
    <h3>商家管理 - 添加店铺</h3>
    <el-form :model="merchantDto" ref="merchantForm" label-width="120px" :rules="rules">
      <el-form-item label="店铺名称" prop="shopName">
        <el-input v-model="merchantDto.shopName" placeholder="请输入店铺名称"></el-input>
      </el-form-item>
      <el-form-item label="店铺地址" prop="address">
        <el-input v-model="merchantDto.address" placeholder="请输入店铺地址"></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input v-model="merchantDto.contactPhone" placeholder="请输入联系电话"></el-input>
      </el-form-item>
      <el-form-item label="店铺头像">
        <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="customUpload"
        >
          <div class="avatar-wrapper">
            <img
                v-if="merchantDto.shopAvatar"
                :src="merchantDto.shopAvatar"
                class="avatar-image"
            />
            <div v-else class="avatar-placeholder">
              <el-icon class="upload-icon"><Plus /></el-icon>
              <span class="upload-text">上传店铺头像</span>
            </div>
            <div class="upload-mask">
              <el-icon class="upload-icon"><Edit /></el-icon>
              <span class="upload-text">更换头像</span>
            </div>
          </div>
          <div class="mt-2 text-sm text-gray-500">店铺头像为可选，不上传将使用默认头像</div>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addStore">添加店铺</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import {ref, reactive} from 'vue';
import {ElMessage} from 'element-plus';
import axios from 'axios';
import {Plus, Edit} from '@element-plus/icons-vue'

// 从localStorage获取用户信息
const userStr = localStorage.getItem('merchant');
const user = userStr ? JSON.parse(userStr) : null;

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';

// 定义表单数据
const merchantDto = ref({
  shopName: '',
  address: '',
  contactPhone: '',
  shopAvatar: '',
  status: 0, // 默认为待审核状态
  userId: user?.id || null // 从localStorage获取用户ID
});

// 表单验证规则
const rules = reactive({
  shopName: [
    {required: true, message: '请输入店铺名称', trigger: 'blur'},
    {min: 2, max: 100, message: '店铺名称长度在2-100个字符之间', trigger: 'blur'}
  ],
  address: [
    {required: true, message: '请输入店铺地址', trigger: 'blur'},
    {max: 255, message: '店铺地址不能超过255个字符', trigger: 'blur'}
  ],
  contactPhone: [
    {required: true, message: '请输入联系电话', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur'}
  ],
  userId: [
    {required: true, message: '用户ID不能为空', trigger: 'blur'}
  ]
});

// 表单引用
const merchantForm = ref(null);

// 自定义上传
const customUpload = async (options) => {
  const {file} = options;
  try {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('userId', user?.id || '123');

    const response = await axios.post(`${BASE_URL}/v1/file/upload`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${user?.token || ''}`
      }
    });

    if (response.data.code === 2000) {
      ElMessage.success('头像上传成功');
      merchantDto.value.shopAvatar = response.data.data;
    } else {
      throw new Error(response.data.message || '上传失败');
    }
  } catch (error) {
    ElMessage.error('上传出错：' + error.message);
    throw error;
  }
};

// 上传前校验
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!');
    return false;
  }

  return isImage && isLt5M;
};

// 定义添加店铺方法
const addStore = async () => {
  // 表单验证
  merchantForm.value.validate(valid => {
    if (!valid) {
      ElMessage.error('请完善店铺信息');
      return;
    }

    // 如果没有上传头像，使用默认头像
    // if (!merchantDto.value.shopAvatar) {
    //   merchantDto.value.shopAvatar = defaultAvatar;
    // }

    // 发送添加店铺请求
    axios.post(`${BASE_URL}/api/v1/merchant/addStore`, merchantDto.value, {
      withCredentials: true
    })
        .then(response => {
          if (response.data.code === 2000) {
            ElMessage.success('店铺添加成功');
            // 清空表单
            merchantDto.value = {
              shopName: '',
              address: '',
              contactPhone: '',
              shopAvatar: '',
              status: 0,
              userId: user?.id || null
            };
          } else {
            ElMessage.error(response.data.msg || '添加店铺失败');
          }
        })
        .catch(error => {
          console.error('添加店铺失败:', error);
          ElMessage.error('添加店铺失败，请稍后重试');
        });
  });
};
</script>

<style scoped>
.avatar-uploader {
  --el-avatar-size: 178px;
}

.avatar-wrapper {
  position: relative;
  width: var(--el-avatar-size);
  height: var(--el-avatar-size);
  border-radius: 6px;
  overflow: hidden;
  border: 1px dashed var(--el-border-color);
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  color: #8c939d;
  background-color: #f5f7fa;
}

.upload-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-wrapper:hover .upload-mask {
  opacity: 1;
}

.upload-icon {
  font-size: 28px;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 14px;
}

.mt-2 {
  margin-top: 0.5rem;
}

.text-sm {
  font-size: 0.875rem;
  line-height: 1.25rem;
}

.text-gray-500 {
  color: #6b7280;
}
</style>